<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /**
     * LRU最近最少使用缓存机制，能get、set
     * 缓存达到上限是删除最近最少使用的数据
     */
    class LRUCache{
      constructor(num){
        this.capacity = num // 缓存容量
        this.map = new Map()
      }
      get(key){
        if(this.map.has(key)){
          let val = this.map.get(key)
          this.map.delete(key) 
          this.map.set(key,val)
          return val
        }else{
          return -1
        }
      }
      put(key,value){
        // 已经存在key，删掉重新存
        if(this.map.has(key)){
          this.map.delete(key)
          this.map.set(key,value)
        }else if(this.capacity <= this.map.size){  // 满了
          this.map.set(key,value)
          this.map.delete(cache.map.keys().next().value)
        }else{  // 没满
          this.map.set(key,value)
        }
      }
    }
    var cache = new LRUCache(2)
    cache.put("a","1")
    cache.put("b","2")
    cache.put("c","3")
    console.log(cache.get("a"))
    console.log(cache.get("b"))
    cache.put('d',6)
    cache.put('e',6)
  </script>
</body>
</html>